from typing import Any, List, Tuple
import logging

from interfaces.form_metadata import IFormMetadataProvider
from common.loaders.model_loader import load_form_all_data


class FormMetadataProvider(IFormMetadataProvider):
    def get_targets(self, filter_attr: Tuple[str, Any], target_attr: str, deduplicate: bool = False) -> List[Any]:
        try:
            filter_name, filter_value = filter_attr
            all_form_objs = load_form_all_data()
            target_values: List[Any] = []
            for form_obj in all_form_objs:
                if not hasattr(form_obj, filter_name):
                    raise AttributeError(f"FormAll对象不存在属性: {filter_name}")
                if not hasattr(form_obj, target_attr):
                    raise AttributeError(f"FormAll对象不存在属性: {target_attr}")
                if getattr(form_obj, filter_name) == filter_value:
                    target_values.append(getattr(form_obj, target_attr))
            if deduplicate:
                target_values = list(dict.fromkeys(target_values))
            return target_values
        except Exception as e:
            logging.error(f"获取目标属性值时发生错误: {str(e)}")
            raise

    def get_column_data(self, header: str, deduplicate: bool = False) -> List[Any]:
        try:
            all_data = load_form_all_data()
            if not all_data:
                raise ValueError("数据为空，无法获取列数据")
            sample_obj = all_data[0]
            if not hasattr(sample_obj, header):
                raise AttributeError(f"FormAll对象没有属性 '{header}'")
            column_data = [getattr(obj, header) for obj in all_data]
            if deduplicate:
                column_data = list(dict.fromkeys(column_data))
            return column_data
        except Exception as e:
            logging.error(f"获取列数据时发生错误: {str(e)}")
            raise
